import cv2
import numpy as np
import json
'''
Created on Nov 5, 2012

@author: x220
'''

    
class contourDetectionSoble:
    def __init__(self,debug=False,thresholdValue=50,contourSize=1000):
        self.debug=debug
        self.thresholdValue=thresholdValue
        self.oldframe = None
        self.controurSize = contourSize
        if(self.debug):
            cv2.namedWindow('edge')
            cv2.createTrackbar('thresholdValue', 'edge', 0, 255, self._callbak)
            cv2.createTrackbar('controurSize', 'edge', 0, 5000, self._callbak)
    
    
    def _callbak(self,*arg):
        self.thresholdValue = cv2.getTrackbarPos('thresholdValue', 'edge')
        self.controurSize = cv2.getTrackbarPos('controurSize', 'edge')
        self.proces(self.oldframe)
    
    def proces(self, frame): 
        self.oldframe = frame  
        scale = 4
        ddepth = cv2.CV_16S    
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)        
        # Gradient-X
        grad_x = cv2.Sobel(gray,ddepth,1,0,ksize = 1, scale = scale,borderType = cv2.BORDER_DEFAULT)
        # Gradient-Y
        grad_y = cv2.Sobel(gray,ddepth,0,1,ksize = 1, scale = scale, borderType = cv2.BORDER_DEFAULT)
        
        abs_grad_x = cv2.convertScaleAbs(grad_x)   
        abs_grad_y = cv2.convertScaleAbs(grad_y)
        
        edge = cv2.addWeighted(abs_grad_x,0.5,abs_grad_y,0.5,0)
        edge =cv2.threshold(edge, self.thresholdValue, 255, cv2.THRESH_BINARY)[1]
        
        if(self.debug):
            cv2.imshow('edge',edge)
        contours, temp = cv2.findContours(edge, cv2.RETR_LIST ,cv2.CHAIN_APPROX_NONE)
        contoursWithCorrectSize = []  
        if(len(contours) != 0):
            for contour in contours:
                if(cv2.contourArea(contour)>self.controurSize):
                        for cordinate in contour:
                            contoursWithCorrectSize.append(int(cordinate[0][0]))
                            contoursWithCorrectSize.append(int(cordinate[0][1]))
        return contoursWithCorrectSize
    
    def getJsonString(self,data):
        return str(json.dumps(data))
        
    def show(self,contours,frame=None):
        if frame==None:
            frame = np.empty(self.oldframe.shape)
        for i in range(0,len(contours),2):
            cord = (contours[i],contours[i+1])
            cv2.line(frame, cord, cord,(0,0,255),2)
        cv2.imshow("contours", frame)